﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Configuration;

namespace SYADynamicDNSUpdater
{
    public partial class SYADynamicDnsUpaterService : ServiceBase
    {

        private bool stopping;
        private ManualResetEvent stoppedEvent;
        StatusChecker sc = new StatusChecker();
        int CheckPeriod { get; set; }

        public SYADynamicDnsUpaterService()
        {
           

            InitializeComponent();
            if (!System.Diagnostics.EventLog.SourceExists("SYADynamicDNSUpdaterSource"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                    "SYADynamicDNSUpdaterSource", "");
            }
            eventLog1.Source = "SYADynamicDNSUpdater";
            eventLog1.Log = "";


            this.stopping = false;
            this.stoppedEvent = new ManualResetEvent(false);

          
        }

        protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry("SYADynamicDNSUpdater Starting Service");
            CheckPeriod =SYADynamicDNSUpdater.Properties.Settings.Default.checkPeriod;
            ThreadPool.QueueUserWorkItem(new WaitCallback(ServiceWorkerThread));
        }

        protected override void OnStop()
        {
            eventLog1.WriteEntry("SYADynamicDNSUpdater Stopping Service");
            this.stopping = true;
            this.stoppedEvent.WaitOne();
        }


        private void ServiceWorkerThread(object state)
        {
            int timer=0;
            sc.CheckIP(eventLog1);//initial check
            // Periodically check if the service is stopping.
            while (!this.stopping)
            {

                if (timer >= CheckPeriod)
                {
                    eventLog1.WriteEntry("SYADynamicDNSUpdater waking up to checking IP");
                    sc.CheckIP(eventLog1);
                    timer = 0;
                }
                
                Thread.Sleep(1000);  //need to wake up and check if the service needs to stop
                timer = timer + 1000;
            }
            
            // Signal the stopped event.
            this.stoppedEvent.Set();
        }
    }
}
